package com.yaocw.baseproject.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.core.content.FileProvider;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import com.flyco.tablayout.CommonTabLayout;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import com.yaocw.baseproject.R;
import com.yaocw.baseproject.adapter.MainPagerAdapter;
import com.yaocw.baseproject.entity.TabEntity;
import com.yaocw.baseproject.fragment.HomeFragment;
import com.yaocw.baseproject.fragment.MineFragment;
import com.yaocw.baseproject.fragment.NewsFragment;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;

public class MainActivity extends BaseActivity {

    private String[] mTitles = {"首页", "资讯", "我的"};
    private int[] mIconUnselectIds = {
            R.mipmap.home_unselect, R.mipmap.collect_unselect,
            R.mipmap.my_unselect};
    private int[] mIconSelectIds = {
            R.mipmap.home_selected, R.mipmap.collect_selected,
            R.mipmap.my_selected};
    private ArrayList<Fragment> mFragments = new ArrayList<>();
    private ArrayList<CustomTabEntity> mTabEntities = new ArrayList<>();
    private ViewPager viewPager;
    private CommonTabLayout commonTabLayout;

    private Uri capturePhotoUrl;

    @Override

    protected int initLayout() {
        return R.layout.activity_main;
    }

    @Override
    protected void initView() {
        viewPager = findViewById(R.id.vp_viewpager);
        commonTabLayout = findViewById(R.id.ctl_common_tab_layout);
    }

    @Override
    protected void initData() {
        mFragments.add(HomeFragment.newInstance());
        mFragments.add(NewsFragment.newInstance());
        mFragments.add(MineFragment.newInstance());

        for (int i = 0; i < mTitles.length; i++) {
            mTabEntities.add(new TabEntity(mTitles[i], mIconSelectIds[i], mIconUnselectIds[i]));
        }

        commonTabLayout.setTabData(mTabEntities);
        commonTabLayout.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                viewPager.setCurrentItem(position);
            }

            @Override
            public void onTabReselect(int position) {
            }
        });

        viewPager.setOffscreenPageLimit(mFragments.size());
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                commonTabLayout.setCurrentTab(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        viewPager.setAdapter(new MainPagerAdapter(getSupportFragmentManager(), MainPagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT, mTitles, mFragments));
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case MineFragment.FETCH_WRITE_AUTH_FOR_ALBUM: {
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    openAlbum();
                } else {
                    showToast("你已拒绝开启该权限");
                }
                break;
            }
            case MineFragment.FETCH_WRITE_AUTH_FOR_CAMERA: {
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    openCamera();
                } else {
                    showToast("你已拒绝开启该权限");
                }
                break;
            }
        }
    }


    private void openCamera() {
        File outputImage = new File(MineFragment.captureOutputPath);
                /*
                创建一个File文件对象，用于存放摄像头拍下的图片，我们把这个图片命名为output_image.jpg
                并把它存放在应用关联缓存目录下，调用getExternalCacheDir()可以得到这个目录，为什么要
                用关联缓存目录呢？由于android6.0开始，读写sd卡列为了危险权限，使用的时候必须要有权限，
                应用关联目录则可以跳过这一步
                 */
        try//判断图片是否存在，存在则删除在创建，不存在则直接创建
        {
            if (!outputImage.getParentFile().exists()) {
                outputImage.getParentFile().mkdirs();
            }
            if (outputImage.exists()) {
                outputImage.delete();
            }

            outputImage.createNewFile();

            if (Build.VERSION.SDK_INT >= 24) {
                MineFragment.captureImageUri = FileProvider.getUriForFile(this,
                        "com.example.mydemo.fileprovider", outputImage);
            } else {
                MineFragment.captureImageUri = Uri.fromFile(outputImage);
            }

            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, MineFragment.captureImageUri);
            startActivityForResult(intent, MineFragment.CAPTURE_PHOTO);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void openAlbum() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("image/*");
        startActivityForResult(intent, MineFragment.PICK_PHOTO);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

//        showToast("requestCode: " + requestCode + "     resultCode: " + resultCode);

        if (RESULT_OK == resultCode) {
            switch (requestCode) {
                case MineFragment.CAPTURE_PHOTO: {
                    Bitmap bitmap = null;
                    try {
                        bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(MineFragment.captureImageUri));
                        AlertDialog.Builder customizeDialog =
                                new AlertDialog.Builder(this);

                        final View dialogView = LayoutInflater.from(this)
                                .inflate(R.layout.dialog_show_image, null);
                        ImageView ivShow = dialogView.findViewById(R.id.iv_show);
                        ivShow.setImageBitmap(bitmap);
                        customizeDialog.setTitle("图片");
                        customizeDialog.setView(dialogView);
                        customizeDialog.setPositiveButton("关闭",
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        showToast("已关闭图片页面");
                                    }
                                });
                        customizeDialog.show();
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                    break;
                }
                case MineFragment.PICK_PHOTO: { // 选择照片：当选择完相片，就会回到这里，然后相片的相关信息会保存在data中，后面想办法取出来
                    //通过getData方法取得它的图片地址，后面的操作都是对这个地址的解析
                    //选择了一张在相册中id为26的照片，它的uri地址如下：
                    //uri=content://com.android.providers.media.documents/document/image%3A26
                    Uri uri = data.getData();
                    if (DocumentsContract.isDocumentUri(this, uri)) {
                        //判断是document类型的图片，所以获取它的doc id
                        //docId是将该资源的关键信息提取出来，比如该资源是一张id为26的image
                        String docId = DocumentsContract.getDocumentId(uri);//docId=image:26

                        //获取它的uri的已解码的授权组成部分，来判断这张图片是在相册文件夹下还是下载文件夹下
                        //在相册文件夹的照片标识字段如下
                        //uri_getAuthority=com.android.providers.media.documents
                        String uri_getAuthority = uri.getAuthority();

                        //注意这里的字符串很容易写错，providers和documents都是有带s的
                        if ("com.android.providers.media.documents".equals(uri_getAuthority)) {
                            //当判断该照片在相册文件夹下时，使用字符串的分割方法split将它id取出来
                            String id = docId.split(":")[1];//id="26"
                            Uri baseUri = Uri.parse("content://media/external/images/media");

                            AlertDialog.Builder customizeDialog =
                                    new AlertDialog.Builder(this);

                            final View dialogView = LayoutInflater.from(this)
                                    .inflate(R.layout.dialog_show_image, null);
                            ImageView ivShow = dialogView.findViewById(R.id.iv_show);
                            ivShow.setImageURI(Uri.withAppendedPath(baseUri, id));

                            customizeDialog.setTitle("图片");
                            customizeDialog.setView(dialogView);
                            customizeDialog.setPositiveButton("关闭",
                                    new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            showToast("已关闭图片页面");
                                        }
                                    });
                            customizeDialog.show();
                        }
                    }
                }
                case MineFragment.SCAN_QR_CODE: {
                    IntentResult intentResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
                    if (intentResult != null) {
                        if (intentResult.getContents() == null) {
                            showToast("扫描失败");
                        } else {
                            String result = intentResult.getContents();
                            showToast(result);
                        }
                    }
                }
            }
        }
    }
}